package com.common.auth.controller;

import com.common.api.annontation.Authority;
import com.common.api.annontation.ServiceLog;
import com.common.api.enums.OperateEnum;
import com.common.auth.api.dto.OrganizationDto;
import com.common.auth.api.service.OrganizationService;
import com.common.auth.util.AuthConstant;
import com.common.tools.util.BaseBusyServiceUtil;
import com.common.web.annotation.ControllerRequest;
import com.common.web.controller.BaseController;
import com.common.web.dto.response.RestResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 组织机构表前端控制器
 * </p>
 * @author liuchao
 */
@ServiceLog
@ControllerRequest("/organization/")
@Api(tags = "系统授权-组织机构接口")
public class OrganizationController extends BaseController {

	@Autowired
	private OrganizationService organizationService;


	/**
	 * 查询组织机构树集合
	 *  需求：用户在组织机构上面的输入框里通过输入组织机构名称，
	 *  	前端可以进行过滤拿到该组织机构的结果。
	 * @param
	 * @return
	 */
	@ApiOperation(value = "查询组织机构树集合")
	@RequestMapping(value="queryOrgTreeList")
	public RestResponse queryOrgTreeList() {
		try {
			List<OrganizationDto> organizationDtos = organizationService.queryOrgTreeList();
			return RestResponse.success("查询组织机构成功！").setData(organizationDtos);
		} catch (Exception e) {
			return RestResponse.failure("查询组织机构失败：" + e.getMessage());
		}
	}


	/**
	 * 保存组织机构信息
	 * @param dto
	 * @return
	 */
	@RequestMapping(value="savaOrgInfo")
	@ApiOperation(value ="保存组织机构信息")
	@Authority(authous = { "organization/organizationEdit" })
    public RestResponse savaOrgInfo(@RequestBody OrganizationDto dto) {
		String operation = StringUtils.isBlank(dto.getId()) ? OperateEnum.addOrg.getEnumName() : OperateEnum.updateOrg.getEnumName();
		try {
			executeOrgOperation(dto, operation);
			return RestResponse.success("组织机构信息保存成功！");
		} catch (Exception e) {
			return RestResponse.failure(operation + "失败：" + e.getMessage());
		}
    }

	private void executeOrgOperation(OrganizationDto dto, String operation) {
		if (OperateEnum.addOrg.getEnumName().equals(operation)) {
			organizationService.add(dto);
			logOperateDetails(OperateEnum.addOrg, dto.getOrganizationCode(), dto);
		} else if (OperateEnum.updateOrg.getEnumName().equals(operation)){
			organizationService.modify(dto);
			logOperateDetails(OperateEnum.updateOrg, dto.getOrganizationCode(), dto);
		}
	}

	private void logOperateDetails(OperateEnum operateEnum, String orgCode, OrganizationDto dto) {
		BaseBusyServiceUtil.addOperateLog(operateEnum, orgCode, dto);
	}

        	
	/**
	 * 根据主键删除组织机构：
	 *  删除组织机构的时候，如果当前组织机构有下级机构，则提示先要删除下级机构，再删除当前机构
	 *  组织机构不做批量删除
	 * @param
	 * @return
	 */
	@RequestMapping(value="deleteOrgById")
	@ApiOperation(value ="根据主键删除组织机构")
	@Authority(authous = { "organization/organizationEdit" })
	public RestResponse deleteOrgById(@RequestBody String orgId) {
		try {
			// 权限验证
			if (!hasDeletePermission()) {
				return RestResponse.failure("无权删除组织机构！");
			}
			organizationService.deleteOrgById(orgId);
			String logMessage = "删除组织机构ID：" + orgId + "，成功！";
			BaseBusyServiceUtil.addOperateLog(OperateEnum.removeOrg, getUserCode(), logMessage);
			return RestResponse.success("组织机构删除成功!");
		} catch (Exception e) {
			return RestResponse.failure("删除组织机构失败：" + e.getMessage());
		}
	}


	/**
	 * 只有管理员才有删除菜单的权限
	 * @return
	 */
	private boolean hasDeletePermission() {
		String userCode = getUserCode();
		return Objects.equals(AuthConstant.ADMIN_USER, userCode);
	}

}
